<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#box{
				width: 100px;
				height: 100px;
				background-color: #009F95;
				position: absolute;
				left: 100px;
			}
		</style>
	</head>
	<body>
		<div id="box">
			
		</div>
		<button id="start">开始</button>
		<script type="text/javascript">
			var oBtn = document.getElementById("start")
			var oBox = document.getElementById("box")

			oBtn.onclick = function  () {
				move(oBox, 10,300,"left",100,function(){
					move(oBox,-10,0,"left")
				})
			}
			function move(obj,step,target,direction,speed,callback) {
				//给speed默认值
				var speed = speed || 100
				clearInterval(obj.timer) //第一次清除 undefined 不会报错
				obj.timer = setInterval(function() {
					//49 步长  100  
					//根据step的符号来判断方向 + 从左往右  - 从右往左
					var attrValue = parseInt(getStyle(obj, direction)) + step
					if ((step > 0 && attrValue > target) || (step < 0 && attrValue < target)) {
						attrValue = target
					}

					obj.style[direction] = attrValue + "px"

					if(attrValue == target) {
						clearInterval(obj.timer)
						console.log(callback)
						//如果运行完成，需要做一些操作,callback函数是等到运行结束以后，再执行，回调函数
						callback && callback()
					}
				}, speed)
			}
			function getStyle(obj,attr){
				return window.getComputedStyle ? window.getComputedStyle(obj)[attr] : obj.currentStyle[attr]
			}

		</script>
	</body>
</html>
